<template>
  <div class="app-container">
    <el-divider>
      <div class="my-divider">基础信息</div>
    </el-divider>

    <el-form
      :model="form"
      ref="form"
      size="small"
      label-width="80px"
      label-position="left"
      :rules="rules"
    >
      <el-form-item label="BOM版本" prop="bomVersion">
        <el-input-number
          v-model="form.bomVersion"
          clearable
          class="my-input"
          :precision="1"
          :step="0.1"
          :min="1"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="bomPdCode">
        <el-input
          v-if="form.bomCode"
          :value="selectedProduct.pdName"
          class="my-input"
          disabled
        />
        <MyPopoverBtn v-else
                      placeholder="请选择产品"
                      :content="selectedProduct.pdName"
                      @click="() => productDialogVisible = true"
        />
      </el-form-item>
      <el-form-item label="产品编号">
        <el-input
          :value="selectedProduct.pdCode"
          :disabled="true"
          class="my-input"
        />
      </el-form-item>
      <el-form-item label="规格型号">
        <el-input
          :value="selectedProduct.pdSpecType"
          :disabled="true"
          class="my-input"
        />
      </el-form-item>
      <el-form-item label="单位">
        <el-input
          :value="selectedProduct.gbsGoodUnit ? selectedProduct.gbsGoodUnit.guName: ''"
          :disabled="true"
          class="my-input"
        />
      </el-form-item>
      <el-form-item label="日产量" prop="bomDailyOutput">
        <el-input-number
          v-model="form.bomDailyOutput"
        />
      </el-form-item>
      <el-form-item label="备注" prop="bomDesc" class="my-desc">
        <el-input
          type="textarea"
          :autosize="{ minRows: 3 }"
          placeholder="请输入备注"
          v-model="form.bomDesc"
        />
      </el-form-item>
    </el-form>

    <el-divider>
      <div class="my-divider">物料配件</div>
    </el-divider>
    <el-button type="primary" @click="handleToAddBomMaterial">添加</el-button>
    <el-button type="primary" plain :disabled="!removeGoods || removeGoods.length === 0"
               @click="handleRemoveBomMaterial"
    >移除
    </el-button>
    <el-table
      :data="selectedMaterials"
      @selection-change="selectChangeRemoveGood"
    >
      <el-table-column
        type="selection"
        align="center"
      />
      <el-table-column
        type="index"
        align="center"
        label="序号"
      />
      <el-table-column label="物料编码" align="center" prop="pdCode" />
      <el-table-column label="物料名称" align="center" prop="pdName" />
      <el-table-column label="规格型号" align="center" prop="pdSpecType" />
      <el-table-column label="单位" align="center" prop="gbsGoodUnit.guName">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="handleRBomMaterialRow(scope.$index, selectedMaterials)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-divider>
      <div class="my-divider">工艺路线</div>
    </el-divider>
    <div v-if="form.bomPdCode && form.bomRoute">
      <el-descriptions :column="2" v-if="routeParams">
        <el-descriptions-item label="工艺路线名称">{{ routeParams.prouteName }}</el-descriptions-item>
        <el-descriptions-item label="工艺路线编号">{{ routeParams.prouteCode }}</el-descriptions-item>
      </el-descriptions>
      <el-tabs v-if="routeParams.procedureParams && routeParams.procedureParams.length > 0">
        <el-tab-pane v-for="(tab, index) in routeParams.procedureParams"
                     :key="tab.procedureCode"
                     :label="tab.procedureName"
        >
          <span slot="label">
            <MyTabPaneLabel :prefix-num="index + 1" :content="tab.procedureName" />
          </span>
          <el-button type="primary" @click="handleToAddMaterial(index)">添加</el-button>
          <el-table
            :data="routeParams.procedureParams[index].pbsProcedureMaterialList"
          >
            <el-table-column
              type="selection"
              align="center"
            />
            <el-table-column type="index" align="center" label="序号" />
            <el-table-column label="物料编号" align="center" prop="pdCode" />
            <el-table-column label="物料名称" align="center" prop="pdName" />
            <el-table-column label="规格型号" align="center" prop="pdSpecType" />
            <el-table-column label="单位" align="center" prop="gbsGoodUnit.guName" />
            <el-table-column label="计划用料" align="center" prop="procedureMNum" width="150">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.procudereMNum"
                  :precision="2"
                  style="width: 135px"
                  size="small"
                  :min="1"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  v-hasPermi="['gbs:bom:edit']"
                  @click="handleRPMaterialRow(index,scope.$index)"
                >移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-empty v-else-if="form.bomPdCode && !form.bomRoute" description="该产品还没有工艺路线" />
    <el-empty v-else description="请选择产品" />

    <!-- 提交按钮 -->
    <MyConfirmBtnGroup :after-cancel-open-page="backPage" :ok-event="submitForm" />

    <!--    选择产品-->
    <MyGoodDialog title="选择产品"
                  v-model="productDialogVisible"
                  :good.sync="selectedProduct"
                  :showTabs="false"
                  :single-mode="true"
                  show-content="both"
                  @closeDialog="productAfterClose"
    />

    <!--    当前的产品选择物料配件-->
    <MyGoodDialog title="选择物料配件"
                  v-model="materialsDialogVisible"
                  :goods.sync="selectedMaterials"
                  :show-tabs="false"
                  :single-mode="false"
                  show-content="both"
    />

    <el-dialog title="选择工序物料" :visible.sync="pMaterialsDialogVisible">
      <el-table
        ref="pMTable"
        @selection-change="handleChangePMaterials"
        :data="allMaterials"
        style="height: 260px;overflow: auto"
        :reverse-selection="true"
        row-key="pdCode"
      >
        <el-table-column
          type="selection"
          align="center"
        />
        <el-table-column
          type="index"
          align="center"
          label="序号"
        />
        <el-table-column label="产品编码" align="center" prop="pdCode" width="125" show-overflow-tooltip />
        <el-table-column label="产品名称" align="center" prop="pdName" width="125" show-overflow-tooltip />
        <el-table-column label="规格型号" align="center" prop="pdSpecType" show-overflow-tooltip />
        <el-table-column label="单位" align="center" prop="gbsGoodUnit.guName" show-overflow-tooltip />
        <el-table-column label="产品类型" align="center" prop="pdGoodType" show-overflow-tooltip>
          <template slot-scope="scope">
            <dict-tag :options="getGbsGoodType" :value="scope.row.pdGoodType" />
          </template>
        </el-table-column>
        <el-table-column label="产品属性" align="center" prop="pdGoodAttr" show-overflow-tooltip>
          <template slot-scope="scope">
            <dict-tag :options="getGbsGoodAttr" :value="scope.row.pdGoodAttr" />
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="my-dialog-footer">
        <el-button @click="cancelPMaterialDialog">取 消</el-button>
        <el-button type="primary" @click="okPMaterialDialog">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MyConfirmBtnGroup from '@/components/MyConfirmBtnGroup/index.vue'
import MyPopoverBtn from '@/components/MyPopoverBtn/index.vue'
import MyGoodDialog from '@/components/MyGoodDialog/index.vue'
import MyRadio from '@/components/MyRadio/index.vue'
import MyTabPaneLabel from '@/components/MyTabPaneLabel/index.vue'
import { addBom, getBom } from '@/api/yyj/gbs/bom'
import { listProcedureMaterial } from '@/api/yyj/pbs/procedureMaterial'

export default {
  name: 'Change',
  components: { MyTabPaneLabel, MyRadio, MyGoodDialog, MyPopoverBtn, MyConfirmBtnGroup },
  dicts: ['gbs_good_type', 'gbs_good_attr'],
  data() {
    return {
      backPage: '/gbs/bom',
      productDialogVisible: false,
      materialsDialogVisible: false,
      tabDialogVisible: false,
      // 表单参数
      form: {
        bomVersion: '1'
      },
      // 表单校验
      rules: {
        bomVersion: [
          { required: true, message: 'BOM版本不能为空', trigger: 'blur' }
        ],
        bomRoute: [
          { required: true, message: '工艺路线不能为空', trigger: 'blur' }
        ],
        bomDailyOutput: [
          { required: true, message: '日产量不为空', trigger: 'blur' }
        ]
      },
      // 选择的产品
      selectedProduct: {},
      // 添加的物料配件
      selectedMaterials: [],
      // 准备移除的物料配件
      removeGoods: [],
      // 选择的工艺路线
      route: {},
      // 此工艺路线下的工序 routeProcedures 需要从物料配件中添加
      routeProcedures: [],
      // 工序物料
      procedureMaterials: [],
      // 当前的tab
      currentIndex: {},
      bomCode: '',
      bomVersion: '',
      routeParams: [],
      // 所有工序物料
      allMaterials: [],
      pMaterialLoading: true,
      pMaterials: [],
      pMaterialTotal: 0,
      pMaterialQueryParams: {
        pageNum: 1,
        pageSize: 5
      },
      prePMaterials: [],
      pMaterialsDialogVisible: false
    }
  },
  computed: {
    getGbsGoodType() {
      return this.dict.type.gbs_good_type
    },
    getGbsGoodAttr() {
      return this.dict.type.gbs_good_attr
    }
  },
  created() {
    this.bomCode = this.$route.query.bomCode
    this.bomVersion = this.$route.query.bomVersion
    if (this.bomCode && this.bomVersion) {
      this.getDetail(this.bomCode, this.bomVersion)
    } else {
      this.form.bomVersion = 1.0
    }
  },
  methods: {
    // 获取bom详细信息
    async getDetail(bomCode, bomVersion) {
      const res = await getBom({
        bomCode,
        bomVersion
      })
      this.form = res.data
      this.selectedProduct = res.data.gbsGood
      this.selectedMaterials = res.selectedMaterials.map(e => e.gbsMaterial)
      await this.getRoute(this.form.bomRoute)
    },
    // 关闭 product-dialog 时调用
    productAfterClose() {
      if (this.selectedProduct && this.selectedProduct.pdCode) {
        this.form.bomPdCode = this.selectedProduct.pdCode
        if (this.selectedProduct.pdProuteCode && this.selectedProduct.pdProuteCode !== '0') {
          this.form.bomRoute = this.selectedProduct.pdProuteCode
          this.getRoute(this.form.bomRoute)
        }
      }
    },
    // 关闭 procedure-material-dialog
    cancelPMaterialDialog() {
      this.$refs.pMTable.clearSelection()
      this.pMaterialsDialogVisible = false
    },
    // 确认关闭 procedure-material-dialog
    okPMaterialDialog() {
      this.routeParams.procedureParams[this.currentIndex].pbsProcedureMaterialList = this.prePMaterials
      this.routeParams.procedureParams[this.currentIndex].pbsProcedureMaterialList.forEach(e => {
        e.procudereMNum = 1
      })
      this.cancelPMaterialDialog()
    },
    handleChangePMaterials(selection) {
      this.prePMaterials = selection
    },
    // 查询工艺路线
    async getRoute(routeCode) {
      const res = await listProcedureMaterial({
        pmProuteCode: routeCode,
        procedureMBom: this.form.bomCode,
        procedureMBV: this.form.bomVersion
      })
      console.log('res ', res)
      this.routeParams = res.data
      this.routeParams.procedureParams.forEach(e => {
        let a = []
        e.pbsProcedureMaterialList.forEach(e1 => {
          if (!e1.pdCode || e1.pdCode === '0') {
            return false
          }
          a.push({
            ...e1, ...e1.gbsGood
          })
        })
        e.pbsProcedureMaterialList = a
      })
      console.log(this.routeParams.procedureParams)
    },
    // 准备移除物料配件
    selectChangeRemoveGood(selection) {
      this.removeGoods = selection
    },
    // 移除物料配件
    handleRemoveBomMaterial() {
      this.removeGoods.forEach(e1 => {
          this.selectedMaterials =
            this.selectedMaterials.filter(e2 => e2.pdCode !== e1.pdCode)
        }
      )
    },
    // 打开物料配件弹窗
    handleToAddBomMaterial() {
      this.materialsDialogVisible = true
    },
    // 移除物料配件
    handleRBomMaterialRow(index, rows) {
      rows.splice(index, 1)
    },
    // 添加工序物料
    handleToAddMaterial(index) {
      if (!this.selectedMaterials || this.selectedMaterials.length <= 0) {
        this.$modal.msgWarning('请先选择物料')
        return
      }
      this.currentIndex = index
      this.allMaterials = this.selectedMaterials
      this.$nextTick(() => {
        this.routeParams.procedureParams[this.currentIndex].pbsProcedureMaterialList.forEach(e => {
          this.$refs.pMTable.toggleRowSelection(this.allMaterials.find(e2 => e2.pdCode === e.pdCode), true)
        })
      })
      this.pMaterialsDialogVisible = true
    },
    // 行 移除工序物料
    handleRPMaterialRow(PIndex, index) {
      this.routeParams.procedureParams[PIndex].pbsProcedureMaterialList.splice(index, 1)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          if (this.form.bomCode && parseFloat(this.form.bomVersion) === parseFloat(this.bomVersion)) {
            this.$modal.msgError('版本需修改')
            return false
          }
          if (!this.form.bomPdCode || this.form.bomPdCode === '0') {
            this.$modal.msgError('请选择产品')
            return false
          }
          if (!this.form.bomRoute || this.form.bomRoute === '0') {
            this.$modal.msgError('该产品还没有工艺路线')
            return false
          }

          const gbsBomMaterials = this.selectedMaterials.map(e => {
            return {
              bmBomCode: this.form.bomCode,
              bmBomVersion: this.form.bomVersion,
              bmMaterialCode: e.pdCode
            }
          })
          const pbsProcedureMaterials = []
          this.routeParams.procedureParams.forEach(e => {
            e.pbsProcedureMaterialList.forEach(e1 => {
              pbsProcedureMaterials.push({
                pdCode: e1.pdCode,
                procudureCode: e.procedureCode,
                pmProuteCode: this.form.bomRoute,
                procudereMNum: e1.procudereMNum,
                procedureMBom: this.form.bomCode,
                procedureMBV: this.form.bomVersion
              })
            })
          })
          console.log(pbsProcedureMaterials)
          // return
          const data = {
            gbsBom: this.form,
            gbsBomMaterials: gbsBomMaterials,
            pbsProcedureMaterials: pbsProcedureMaterials
          }
          this.$modal.loading('正在提交...')
          await addBom(data)
          if (this.form.bomCode != null) {
            //   await updateBom(data)
            this.$modal.msgSuccess('修改成功')
          } else {
            this.$modal.msgSuccess('新增成功')
          }
          this.afterSubmit()
        }
      })
    },
    afterSubmit() {
      this.$tab.closeOpenPage()
      this.reset()
      this.$tab.refreshPage({
        path: this.backPage
      })
      this.$modal.closeLoading()
    },
    // 表单重置
    reset() {
      this.form = {
        bomCode: null,
        bomPdCode: null,
        gbsGood: {},
        isDefault: null,
        bomVersion: null,
        bomDailyOutput: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        bomDesc: null,
        bomRoute: null
      }
      this.resetForm('form')
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/assets/styles/yyj/change';
</style>
